package com.nali.dal.mongo.dao;

import java.util.List;

import com.mongodb.DBCollection;
import com.mongodb.WriteConcern;
import com.nali.dal.dao.IOperateDao;
import com.nali.dal.exception.SyntaxException;
import com.nali.dal.expression.ExpressionDto;
import com.nali.dal.expression.ExpressionValue;
import com.nali.dal.expression.PropertyExpression;
import com.nali.dal.expression.operate.Modifier;
import com.nali.dal.expression.query.Criteria;
import com.nali.dal.mongo.dao.general.ExceptionTraner;
import com.nali.dal.mongo.explain.operate.PreparedUpdate;
import com.nali.dal.mongo.explain.operate.Update;

public class MongoOperateDao implements IOperateDao {
	private DBCollection collection;
	private WriteConcern concern;

	public MongoOperateDao(DBCollection collection, WriteConcern concern) {
		super();
		this.collection = collection;
		this.concern = concern;
	}

	@Override
	public int upsert(ExpressionDto<Criteria> query, List<ExpressionValue<Modifier>> modifiers, boolean upsert) {
		List<ExpressionValue<Criteria>> expressionValues = query.getExpressionValues();
		List<PropertyExpression<Criteria>> propertyExpressions = query.getPropertyExpressions();
		PreparedUpdate pu = Update.parse(expressionValues, propertyExpressions, modifiers);
		if(pu.getConditionParamSize()!=0) {
			throw new SyntaxException("missing "+pu.getConditionParamSize()+" query value");
		}
		try {
			return pu.update(collection, upsert, concern);
		} catch (Exception e) {
			throw ExceptionTraner.tranException(e);
		}
	}
}
